﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

#if WPF
namespace Silverlight.Hosting.Wpf.Interop
#else
namespace Silverlight.Hosting.Interop
#endif
{
    public sealed class SafeComObject<T> : IDisposable
        where T : class
    {
        public T _comObject;
        private bool _disposed;

        public SafeComObject(T comObject)
        {
            if (comObject == null) throw new ArgumentNullException("comObject");
            _comObject = comObject;
        }

        /// <summary>
        /// Gets the target object
        /// </summary>
        public T Object
        {
            get { return _comObject; }
        }

        ~SafeComObject()
        {
            Dispose(false);
        }

        /// <summary>
        /// Release resources held by the target object
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                Marshal.ReleaseComObject(_comObject);
                _comObject = null;
            }
            _disposed = true;
        }
    }

    internal class SafeComHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        public SafeComHandle(IntPtr handle)
            : base(true)
        {
            SetHandle(handle);
        }

        protected override bool ReleaseHandle()
        {
            Marshal.Release(DangerousGetHandle());
            return true;
        }
    }

}
